#!/bin/bash

# Log Server Linux Service Installation Script

set -e

echo "Installing Log Server as Linux systemd service..."
echo

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "Error: Node.js is not installed"
    echo "Please install Node.js first: https://nodejs.org/"
    exit 1
fi

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "Error: npm is not installed"
    echo "Please install npm first"
    exit 1
fi

echo "Node.js version: $(node --version)"
echo "npm version: $(npm --version)"
echo

# Create service user
echo "Creating service user 'logserver'..."
if ! id "logserver" &>/dev/null; then
    useradd --system --no-create-home --shell /bin/false logserver
    echo "User 'logserver' created successfully"
else
    echo "User 'logserver' already exists"
fi

# Create service directory
echo "Creating service directory..."
SERVICE_DIR="/opt/log-server"
mkdir -p "$SERVICE_DIR"

# Copy application files
echo "Copying application files..."
cp -r ./* "$SERVICE_DIR/"

# Install dependencies
echo "Installing dependencies..."
cd "$SERVICE_DIR"
npm install --production

# Set ownership and permissions
echo "Setting ownership and permissions..."
chown -R logserver:logserver "$SERVICE_DIR"
chmod -R 755 "$SERVICE_DIR"

# Copy systemd service file
echo "Installing systemd service..."
cp "$SERVICE_DIR/log-server.service" /etc/systemd/system/

# Reload systemd and enable service
echo "Configuring systemd service..."
systemctl daemon-reload
systemctl enable log-server.service

echo
echo "Installation completed successfully!"
echo "Service commands:"
echo "  Start:   sudo systemctl start log-server"
echo "  Stop:    sudo systemctl stop log-server"
echo "  Status:  sudo systemctl status log-server"
echo "  Logs:    sudo journalctl -u log-server -f"
echo
echo "Starting service now..."
systemctl start log-server

echo "Service status:"
systemctl status log-server --no-pager